package com.sc.VenusQueryBeta.adapter.account;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.model.sqlite.DataBaseDao;
import com.sc.VenusQueryBeta.model.sqlite.MsgListBean;
import com.sc.VenusQueryBeta.model.sqlite.ReadBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/11/20.
 */

public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.Holder> {
    private final Activity mActivity;
    private List<MsgListBean> groupArrayList;
    //    private List<MsgListBean> datas;
    private DataBaseDao dataBaseDao;
    //    private List<MsgListBean> datas1;
    private Context mContext;
    private List<MsgListBean> msgListBeans12;
    private BuildBean buildBean;
    private ProgressDialog progressDialog;
    private boolean isRead;
    private List<MsgListBean> readBeans1;

    public MsgAdapter(List<MsgListBean> msgListBean, Context mContext, DataBaseDao dataBaseDao, ArrayList<MsgListBean> group, Activity mActivity, List<MsgListBean> readBeans) {
        this.mContext = mContext;
        this.mActivity = mActivity;
        this.dataBaseDao = dataBaseDao;
        this.msgListBeans12 = msgListBean;
        this.groupArrayList = group;
//        this.groupArrayList = readBeans;

    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(mContext).inflate(R.layout.item_recycler, parent, false);
        return new Holder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        holder.time.setText(groupArrayList.get(position).getSendTime());
        holder.name.setText(groupArrayList.get(position).getSendId());
        LogUtil.e("sms=" + groupArrayList.get(position).getMessageContent().indexOf("\n"));
        if (groupArrayList.get(position).getMessageContent().indexOf("\n") > 0) {
            holder.message.setText(groupArrayList.get(position).getMessageContent().substring(0, groupArrayList.get(position).getMessageContent().indexOf("\n")));
        } else {
            holder.message.setText(groupArrayList.get(position).getMessageContent());
        }
//        if (groupArrayList.get(position).getIsRead().equals("1")) {
//            holder.tv_msg_count.setVisibility(View.GONE);
//        } else {
//            holder.tv_msg_count.setVisibility(View.VISIBLE);
//        }
        SQLiteDatabase rdb1 = dataBaseDao.databasehelper.getWritableDatabase();
        rdb1.beginTransaction();
        try {
        //批量处理操作
            readBeans1 = dataBaseDao.searchAllRead();
            LogUtil.e("readBeans大小："+ readBeans1.size());
            for (int i=0;i<groupArrayList.size();i++) {
                LogUtil.e("readBeans1:==="+groupArrayList.get(i).getSendId());
            }
            isRead = dataBaseDao.searchMessageIsRead(groupArrayList.get(position).getSendId());
            LogUtil.e("isRead："+isRead);
            rdb1.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
        } catch (Exception e) {
            LogUtil.e("Exception"+e.getMessage());
            hideProgressDialog();
        } finally {
//            rdb1.close();
            if (!isRead) {
                holder.tv_msg_count.setVisibility(View.VISIBLE);
            } else {
                holder.tv_msg_count.setVisibility(View.GONE);
            }
            rdb1.endTransaction(); //处理完成

        }
    }

    @Override
    public int getItemCount() {
        return groupArrayList.size();
    }

    public interface OnCliCkItemListener {
        void clickItem(int position, List<MsgListBean> msgListBeans12);
    }

    private OnCliCkItemListener onCliCkItemListenerr;

    public void setOnCliCkItemListenerr(OnCliCkItemListener onCliCkItemListenerr) {
        this.onCliCkItemListenerr = onCliCkItemListenerr;
    }

    class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView name;
        private TextView time;
        private TextView message;
        private TextView tv_msg_count;

        Holder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.hotel_name);
            time = itemView.findViewById(R.id.hotel_phone);
            message = itemView.findViewById(R.id.hotel_adress);
            tv_msg_count = itemView.findViewById(R.id.tv_msg_count);
            View delete = itemView.findViewById(R.id.delete);
            RelativeLayout main = itemView.findViewById(R.id.main);
            main.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (onCliCkItemListenerr != null) {
                        showProgressDialog(mActivity, "加载中");
                        int pos1 = getAdapterPosition();
                        SQLiteDatabase rdb1 = dataBaseDao.databasehelper.getWritableDatabase();
                        rdb1.beginTransaction();
                        try {
                            //批量处理操作
                            msgListBeans12 = dataBaseDao.searchMsg1(groupArrayList.get(pos1).getSendId());
                            dataBaseDao.setMessageIsRead(groupArrayList.get(pos1).getSendId());//點擊就設置已讀信息
//                            MsgListBean msgListBean = groupArrayList.get(pos1);
//                            msgListBean.setIsRead("1");
//                            groupArrayList.set(pos1,msgListBean);
                            rdb1.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交

                        } catch (Exception e) {
                            hideProgressDialog();
                            LogUtil.e("Exception:" + e.getMessage());
                        } finally {
                            rdb1.endTransaction(); //处理完成
//                            ToastUtils.showToast("查询成功");
//                            rdb1.close();
                            LogUtil.e("size=" + msgListBeans12.size());
                            onCliCkItemListenerr.clickItem(getAdapterPosition(), msgListBeans12);
                            hideProgressDialog();
                            notifyDataSetChanged();
                        }
                    }
                }
            });
//          main.setOnClickListener(this);
            delete.setOnClickListener(this);
        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.delete:
                    //先彈出對話框
                    new AlertDialog
                            .Builder(mActivity)
                            .setTitle("删除提示")
                            .setMessage("删除该信息将不可恢复，确定要删除吗")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    showProgressDialog(mActivity, "删除中");
                                    int pos = getAdapterPosition();
                                    //删除数据库
                                    SQLiteDatabase rdb = dataBaseDao.databasehelper.getWritableDatabase();
                                    rdb.beginTransaction();
                                    try {
                                        //批量处理操作
                                        dataBaseDao.deleteMsg(String.valueOf(groupArrayList.get(pos).getSendId()));
                                        rdb.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交

                                    } catch (Exception e) {
                                        hideProgressDialog();
                                    } finally {
                                        rdb.endTransaction(); //处理完成
                                        DialogUIUtils.dismiss(buildBean);
//                        rdb.close();
                                        hideProgressDialog();
                                        Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
                                        intentx.putExtra(Constants.CLOSE_RED, "close");
                                        //发送本地广播
                                        LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
                                    }
                                    groupArrayList.remove(pos);
                                    notifyItemRemoved(pos);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            })
                            .create()
                            .show();

                    break;
            }
        }


    }

    public void showProgressDialog(Context mContext, String text) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        progressDialog.setMessage(text);    //设置内容
        progressDialog.setCancelable(false);//点击屏幕和按返回键都不能取消加载框
        progressDialog.show();
    }

    public void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

}
